package com.doudoukeji.service.Activity.myhospital;

import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.doudoukeji.service.Bean.HospitalLitapal;
import com.doudoukeji.service.Bean.Token;
import com.doudoukeji.service.R;
import com.doudoukeji.service.Utils.ABAppUtil;
import com.doudoukeji.service.Utils.MyToast;
import com.sanhai.android.mvp.EduActivity;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * @version 2.0
 * @类描述： 选择医院列表
 * @项目名称：ddgh
 * @类名称： MyActivity
 * @包名称： com.doudoukeji.service.Activity.my
 * @创建人：张强 boy
 * @创建时间：2016/3/9 14:12
 * @修改人：
 * @修改时间：2016/3/9 14:12
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class HospitalListActivity extends EduActivity implements HospitalListView {
    // topbar部分
    private Button mBtnBack;
    private TextView mTvTitle;

    // 当前界面
    private ListView mListView;
    private IndustryAdapter mAdapter;
    private EditText mEtKeyWord;
    private LinearLayout mLaySearch, mLaySearching;
    private Button mBtnCancel, mBtHospitalListOk;
    private ImageView mIvSearch;
    private HospitalLitapal hospitalBean;
    private List<HospitalLitapal> mDatas;
    private List<HospitalLitapal> mDatasBeijing;
    private List<HospitalLitapal> mDatasGuangzhou;
    private String keyWords;
    private TextView mTvBeijing, mTvGuangzhou;

    private LinearLayout mLlHospitallistBeijing, mLlHospitallistGuangzhou;
    private View mViewHospitallistBeijing, mViewHospitallistGuangzhou;
    private String ADDID_BEIJING = "1000";
    private String ADDID_GUANGZHOU = "1100";
    private String addId;
    private List<String> chiosList = new ArrayList<String>();
    //记录去重位置
    private int deleteNum;

    private HostpitalListPresenter presenter;

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_hospitallist);
        if (StringUtils.isNotBlank(Token.getHospitals())) {
            String[] split = Token.getHospitals().split(",");
            for (int x = 0; x < split.length; x++) {
                chiosList.add(split[x]);
            }
        }
    }

    @Override
    public void init() {
        // topbar部分
        mBtnBack = (Button) findViewById(R.id.btn_back);
        mBtnBack.setOnClickListener(this);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvTitle.setText("选择医院");

        //城市切换卡
        mLlHospitallistBeijing = (LinearLayout) findViewById(R.id.ll_hospitallist_beijing);
        mLlHospitallistGuangzhou = (LinearLayout) findViewById(R.id.ll_hospitallist_guangzhou);
        mLlHospitallistBeijing.setOnClickListener(this);
        mLlHospitallistGuangzhou.setOnClickListener(this);

        mViewHospitallistBeijing = findViewById(R.id.view_hospitallist_beijing);
        mViewHospitallistGuangzhou = findViewById(R.id.view_hospitallist_guangzhou);
        mTvBeijing = (TextView) findViewById(R.id.tv_beijing);
        mTvGuangzhou = (TextView) findViewById(R.id.tv_guangzhou);

        //确定
        mBtHospitalListOk = (Button) findViewById(R.id.bt_hospitallist_ok);
        mBtHospitalListOk.setOnClickListener(this);

        // 当前界面
        addId = ADDID_BEIJING;
        mDatasBeijing = new HospitalLitapal().getHospitallitapalCity(ADDID_BEIJING);
        mDatasGuangzhou = new HospitalLitapal().getHospitallitapalCity(ADDID_GUANGZHOU);
        mDatas = mDatasBeijing;
        //设置mDatas的选中状态
        mDatas = setMDataStatus(mDatas, chiosList);
        mListView = (ListView) findViewById(R.id.listview);
        mAdapter = new IndustryAdapter();
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                //1.判断存储列表中是否有这个元素2.在取消操作是，有这个元素要删除掉，没有则不处理3.在添加操作的时候判断是否有这个元素避免重复
                if (mDatas.get(position).isChoice()) {
                    if (isHave(mDatas, chiosList, position)) {
                        chiosList.remove(deleteNum);
                    }
                } else {
                    if (!isHave(mDatas, chiosList, position)) {
                        chiosList.add(mDatas.get(position).getCityid());
                    }
                }
                mDatas.get(position).setChoice(!mDatas.get(position).isChoice());
                mAdapter.notifyDataSetChanged();
            }
        });
        mLaySearch = (LinearLayout) findViewById(R.id.lay_search);
        mLaySearch.setOnClickListener(this);
        mLaySearching = (LinearLayout) findViewById(R.id.lay_searching);
        //输入的关键字
        mEtKeyWord = (EditText) findViewById(R.id.et_keyword);
        //取消按钮
        mBtnCancel = (Button) findViewById(R.id.btn_cancel);
        mBtnCancel.setOnClickListener(this);
        //搜索图标
        mIvSearch = (ImageView) findViewById(R.id.iv_search);
        mIvSearch.setOnClickListener(this);

        mEtKeyWord.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                keyWords = arg0 + "";
                    mDatas = new HospitalLitapal().getAllHospitallitapal(keyWords, addId);
                    //设置mDatas的选中状态
                    mDatas = setMDataStatus(mDatas, chiosList);
                    mAdapter.notifyDataSetChanged();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub

            }
        });


    }

    /**
     * 遍历存储元组去重id操作
     *
     * @param mDatas
     * @param chiosList
     */
    private boolean isHave(List<HospitalLitapal> mDatas, List<String> chiosList, int position) {
        for (int x = 0; x < chiosList.size(); x++) {
            if (mDatas.get(position).getCityid().equals(chiosList.get(x))) {
                deleteNum = x;
                return true;
            }
        }
        return false;
    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                HospitalListActivity.this.finish();
                break;
            case R.id.lay_search:
                mLaySearching.setVisibility(View.VISIBLE);
                ABAppUtil.showSoftInput(HospitalListActivity.this, mEtKeyWord);
                break;
            case R.id.iv_search:
                if (searchValue()) {
                    mDatas = new HospitalLitapal().getAllHospitallitapal(keyWords, addId);
                    //设置mDatas的选中状态
                    mDatas = setMDataStatus(mDatas, chiosList);
                    mAdapter.notifyDataSetChanged();
                    mLaySearching.setVisibility(View.GONE);
                    mEtKeyWord.setText("");
                }
                break;
            case R.id.btn_cancel:
                //设置mDatas的选中状态
                mDatas = setMDataStatus(mDatas, chiosList);
                mAdapter.notifyDataSetChanged();
                mLaySearching.setVisibility(View.GONE);
                mEtKeyWord.setText("");
                ABAppUtil.hideSoftInput(HospitalListActivity.this, mEtKeyWord);
                break;
            case R.id.ll_hospitallist_beijing:
                addId = ADDID_BEIJING;
                if (mLaySearching.getVisibility() == View.VISIBLE) {
                    mDatas = new HospitalLitapal().getAllHospitallitapal(mEtKeyWord.getText().toString(), addId);
                    //设置mDatas的选中状态
                    mDatas = setMDataStatus(mDatas, chiosList);
                } else {
                    mDatas = mDatasBeijing;
                    //设置mDatas的选中状态
                    mDatas = setMDataStatus(mDatas, chiosList);
                }
                mViewHospitallistBeijing.setVisibility(View.VISIBLE);
                mViewHospitallistGuangzhou.setVisibility(View.GONE);
                mTvBeijing.setTextColor(Color.parseColor("#fcb333"));
                mTvGuangzhou.setTextColor(getResources().getColor(R.color.black));
                mAdapter.notifyDataSetChanged();
                break;
            case R.id.ll_hospitallist_guangzhou:
                addId = ADDID_GUANGZHOU;
                if (mLaySearching.getVisibility() == View.VISIBLE) {
                    mDatas = new HospitalLitapal().getAllHospitallitapal(mEtKeyWord.getText().toString(), addId);
                    //设置mDatas的选中状态
                    mDatas = setMDataStatus(mDatas, chiosList);
                } else {
                    mDatas = mDatasGuangzhou;
                    //设置mDatas的选中状态
                    mDatas = setMDataStatus(mDatas, chiosList);
                }
                mViewHospitallistBeijing.setVisibility(View.GONE);
                mViewHospitallistGuangzhou.setVisibility(View.VISIBLE);
                mTvBeijing.setTextColor(getResources().getColor(R.color.black));
                mTvGuangzhou.setTextColor(Color.parseColor("#fcb333"));
                mAdapter.notifyDataSetChanged();
                break;

            case R.id.bt_hospitallist_ok:
                String pl = "";
                for (int x = 0; x < chiosList.size(); x++) {
                    pl += chiosList.get(x) + ",";
                }
                if (chiosList != null && chiosList.size() > 0) {
                    String substring = pl.substring(0, pl.lastIndexOf(","));

                    presenter = new HostpitalListPresenter(HospitalListActivity.this, HospitalListActivity.this);
                    presenter.updateUserInfo("", "", "", substring, "");
                } else {
                    MyToast.DefaultmakeText(HospitalListActivity.this, "请选择医院", 1);
                }


            default:
                break;
        }
    }

    /**
     * 设置mDatas的选中状态
     *
     * @param mDatas
     * @param chiosList
     */
    private List<HospitalLitapal> setMDataStatus(List<HospitalLitapal> mDatas, List<String> chiosList) {

        //1.为避免总是操作数据库，顾一次将数据取出到集合中，对集合操作
        //2.为避免之前集合中的状态对后面数据精准造成影响，顾遍历对其状态进行复位操作
        for (int x = 0; x < mDatas.size(); x++) {
            mDatas.get(x).setChoice(false);
        }
        // 将以选中的数据标记
        for (int x = 0; x < mDatas.size(); x++) {
            for (int y = 0; y < chiosList.size(); y++) {
                if (mDatas.get(x).getCityid().equals(chiosList.get(y))) {
                    mDatas.get(x).setChoice(true);
                }
            }
        }

        return mDatas;
    }

    @Override
    public void updateSucced(String hospitals) {
        showToastMessage("选择医院成功");
        Token.setHospitals(hospitals);
        this.finish();
    }

    @Override
    public void updateFail() {
        showToastMessage("选择医院失败");
    }

    public class IndustryAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mDatas.size();
        }

        @Override
        public Object getItem(int arg0) {
            return mDatas.get(arg0);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(HospitalListActivity.this)
                        .inflate(R.layout.item_hospital, null);
                holder = new ViewHolder();
                holder.content = (TextView) convertView
                        .findViewById(R.id.tv_content);
                holder.mIvRight = (ImageView) convertView.findViewById(R.id.iv_right);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();// 取出ViewHolder对象
            }

            if (StringUtils.isNotBlank(mDatas.get(position).getName())) {
                holder.content.setText(mDatas.get(position).getName());
            }

            if (mDatas.get(position).isChoice()) {
                holder.mIvRight.setVisibility(View.VISIBLE);
            } else {
                holder.mIvRight.setVisibility(View.GONE);
            }
            return convertView;
        }
    }

    public final class ViewHolder {
        public TextView content;
        public ImageView mIvRight;
    }

    @Override
    public void onBackPressed() {
        if (mLaySearching.getVisibility() == View.VISIBLE) {
            mLaySearching.setVisibility(View.GONE);
        } else {
            HospitalListActivity.this.finish();
        }
        return;
    }

    /**
     * 判断关键字是否是空的
     *
     * @return
     */
    public boolean searchValue() {
        keyWords = mEtKeyWord.getText().toString().trim();
        if (StringUtils.isBlank(keyWords)) {
            Toast.makeText(HospitalListActivity.this, "关键字不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
}
